package cn.zwx.member.svc.service.impl;

import cn.zwx.base.exception.BizWrapException;
import cn.zwx.member.svc.vo.GenCaptchaVO;
import cn.zwx.member.svc.domain.constans.MemberConstant;
import cn.zwx.member.svc.manager.distributed.DistributedManager;
import cn.zwx.member.svc.service.CaptchaService;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangwenxue
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Resource
    private DistributedManager distributedManager;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public GenCaptchaVO getCaptcha() throws BizWrapException {
        // 1.生成验证码
        ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha (110, 36);
        final String verCode = arithmeticCaptcha.text().toLowerCase();
        final String distributedId = distributedManager.getDistributedId();
        // 2.保存到redis
        String redisKey = MemberConstant.CAPTCHA_CACHE_KEY_PREFIX+distributedId;
        redisTemplate.opsForValue().set(redisKey,verCode, MemberConstant.INT_5, TimeUnit.MINUTES);
        // 3.返回参数
        final GenCaptchaVO genCaptchaVO = new GenCaptchaVO();
        genCaptchaVO.setCaptchaId(distributedId);
        genCaptchaVO.setSpecCaptcha(arithmeticCaptcha.toBase64());
        return genCaptchaVO;
    }
}
